<template>
  <div class="content" v-loading="loading">
    <div class="tabInfo">
      <div class="search">
        <!-- 搜索按钮操作 -->
        <div class="left">
          <SearchForm :formObj="formObj" :formData="formInline"></SearchForm>
        </div>
        <div class="button">
          <el-button type="primary" @click="handleExport">导出</el-button>
          <el-button type="primary" @click="handleAdd">新增</el-button>
        </div>
      </div>
      <div class="tabTable">
        <TabTable ref="tableDataRef" :isShowBtn="true" :tableData="tableData" :pagination="pagination"
          @handleInfo="handleInfo" @handleGetApplication="handleGetApplication" @sizeChange="sizeChange"
          @currentChange="currentChange" @handleSelectionChange="handleSelectionChange" @handleAdd="handleAdd">
        </TabTable>
      </div>

    </div>


    <el-dialog destroy-on-close v-model="dialogVisible" width="680px" @close="handleDialogClose">
      <template #title>
        <div class="dialog-title">
          <span class="dialog-title-bar"></span>
          <span class="dialog-title-text">模板信息</span>
        </div>
      </template>
      <el-form :model="formData" :rules="rules" ref="formRef" label-position="right" label-width="100px">
        <el-row :gutter="24">
          <el-col :span="12">
            <el-form-item label="模板名称" prop="name">
              <el-input :disabled="openType === 'info'" v-model="formData.name" placeholder="请输入模板名称" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="版本号" prop="version">
              <el-input :disabled="openType === 'info'" v-model="formData.version" placeholder="请输入版本号" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="24">
          <el-col :span="12">
            <el-form-item label="所属模块" prop="affiliatedModule">
              <el-select :disabled="openType === 'info'" v-model="formData.affiliatedModule" placeholder="请选择">
                <el-option v-for="item in sys_model" :key="item.value" :label="item.label" :value="item.value" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="适用行业" prop="industry">
              <el-select :disabled="openType === 'info'" v-model="formData.industry" placeholder="请选择">
                <el-option v-for="item in sys_industry" :key="item.value" :label="item.label" :value="item.value" />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="24" v-if="openType === 'info'">
          <el-col :span="12">
            <el-form-item label="创建人" prop="createName">
              <el-input :disabled="openType === 'info'" v-model="formData.createName" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="创建时间" prop="createTime">
              <el-input :disabled="openType === 'info'" v-model="formData.createTime" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-form-item label="模板文件" prop="file">
          <Upload :isFileName="true" :onlyView="openType == 'info' ? false : true" v-model="formData.file" :isShowTip="false"
            :fileType="fileType" @update="uploadFiles" @delete="handleFileDelete"></Upload>
          <!-- <el-button v-if="formData.file" type="primary" link style="margin-left: 10px;"
            @click="handlePreviewFile">预览</el-button> -->
        </el-form-item>


        <el-form-item label="备注" prop="remarks">
          <el-input :disabled="openType === 'info'" v-model="formData.remarks" maxlength="2000" type="textarea"
            placeholder="请输入内容" />
        </el-form-item>


        <el-form-item v-if="openType === 'add'" style="text-align:right;">
          <el-button type="primary" @click="handleSubmit">保存</el-button>
          <el-button @click="handleDialogClose">关闭</el-button>
        </el-form-item>
      </el-form>
    </el-dialog>
  </div>
  <PreviewDocx ref="previewDocxRef" />
</template>
<script setup>
import TabTable from "../components/tabTable.vue";
import SearchForm from "@/components/searchForm/index.vue";
import Upload from "@/components/FileUpload/index.vue";
import { pageListTamplate, saveOrUpdate, downloadBatch } from '@/api/system/template'
import {
  ref,
  reactive,
  onMounted,
  onBeforeUnmount,
  getCurrentInstance,
  nextTick,
} from "vue";
import PreviewDocx from "@/components/previewDocx/index.vue";
import { getCommonTableHeight } from "@/utils/commonTableHeight.js";
import { ElMessage } from "element-plus";
const { proxy } = getCurrentInstance();
const { sys_model } = proxy.useDict("sys_model");
const { sys_industry } = proxy.useDict("sys_industry");
const previewDocxRef = ref();
const openType = ref('');
const modelList = reactive([]);
const fileType = ref([
  "doc",
  "docx",
]);
const formObj = reactive({
  item: [
    {
      input: true,
      label: "",
      prop: "name",
      placeholder: "请输入模板名称",
      disabled: false,
    },
    {
      select: true,
      label: "",
      prop: "module",
      placeholder: "请选择所属模块",
      disabled: false,
      options: sys_model,
    },
    {
      select: true,
      label: "",
      prop: "industry",
      placeholder: "请输入适用行业",
      disabled: false,
      options: sys_industry,
    },
  ],
  btn: [
    {
      type: "primary",
      name: "搜索",
      className: "el-button-primary",
      clickFun: () => {
        handleQuery();
      },
    },
    {
      type: "primary",
      name: "重置",
      className: "el-button-primary",
      clickFun: () => {
        resetTabState();
      },
    },

  ],
});
const formInline = reactive({
  pageNum: 1,
  pageSize: 10,
  name: '',
  module: '',
  industry: '',
  // phase: 0,
});
const fileList = ref([]);

const resetTabState = () => {
  // 重置表单字段
  Object.keys(formInline).forEach(key => {
    formInline[key] = '';

  });
  // 重置分页
  formInline.pageNum = 1;
  formInline.pageSize = 10;
  // 重新查询
  getJobList();
};
const loading = ref(false);
const tableData = ref([]);
const pagination = reactive({
  total: 10,
  page: 1,
  limit: 10,
  pageSizes: [10, 20, 30, 50],
});
const tabHeight = ref(0);

// 页面高度
const updateViewportHeight = () => {
  tabHeight.value = getCommonTableHeight();
};
onMounted(() => {
  const routes = sessionStorage.getItem('routes');
  if (routes) {
    modelList.push(...JSON.parse(routes));
  }
  console.log('modelList', modelList);
  getJobList();
});

onBeforeUnmount(() => {
  window.removeEventListener("resize", updateViewportHeight); // 移除监听
});

const dialogVisible = ref(false);
const formData = reactive({
  name: '',
  version: '',
  affiliatedModule: '',
  industry: '',
  file: null,
  remarks: ''
});
const rules = {
  name: [{ required: true, message: '请输入模板名称', trigger: 'blur' }],
  version: [{ required: true, message: '请输入版本号', trigger: 'blur' }],
  affiliatedModule: [{ required: true, message: '请选择所属模块', trigger: 'change' }],
  industry: [{ required: true, message: '请选择适用行业', trigger: 'change' }],
  file: [{ required: true, message: '请上传模板文件', trigger: 'change' }]
};
const formRef = ref();
const handleAdd = () => {
  openType.value = 'add';
  Object.keys(formData).forEach(key => formData[key] = '');
  dialogVisible.value = true;
  formRef.value?.resetFields(); // 清除校验提示
};
const handleDialogClose = () => {
  openType.value = '';
  Object.keys(formData).forEach(key => formData[key] = '');
  dialogVisible.value = false;
};
const handleSubmit = () => {
  formRef.value.validate((valid) => {
    if (valid) {
      console.log('formData', formData);
      saveOrUpdate(formData).then((res) => {
        console.log('res', res);
        if (res.code === 200) {
          ElMessage.success('保存成功');
          dialogVisible.value = false;
          Object.keys(formData).forEach(key => formData[key] = key === 'file' ? null : '');
          getJobList();
        } else {
          ElMessage.error('保存失败');
        }
      })
      // TODO: 提交逻辑
      // dialogVisible.value = false;
      // Object.keys(formData).forEach(key => formData[key] = key === 'file' ? null : '');
    }
  });
};
// 附件
const uploadFiles = (field, files) => {
  // 检查field是否有效
  if (field) {
    formData[field] = files;
  }
};
const handleFileDelete = (updatedFiles, field) => {
  formData[field] = "";
};
const handleSelectionChange = (val) => {
  console.log('val', val);
  if (val) {
    fileList.value = []; // 先清空数组
    val.forEach(item => {
      if (item.file) {
        fileList.value.push(item.file);
      }
    })
  } else {
    fileList.value = []
  }
  // 使用nextTick确保在DOM更新后再打印
  // nextTick(() => {
  //   console.log('fileList', fileList.value);
  // });
}


const handleExport = async () => {
  console.log('fileList', fileList.value);

  if(fileList.value.length === 0){
    ElMessage.warning('请选择要导出文件的数据');
    return;
  }
  loading.value = true;
  try {
    const res = await downloadBatch({pathList:fileList.value});
    if (res) {
      const url = window.URL.createObjectURL(res);
      const link = document.createElement('a');
      link.href = url;
      // 根据文件数量决定下载文件名
      if (fileList.value.length > 1) {
        link.download = `导出文件_${new Date().getTime()}.zip`;
      } else {
        // 从文件路径中获取文件名
        const fileName = fileList.value[0].split('/').pop();
        link.download = fileName || `导出文件_${new Date().getTime()}`;
      }
      document.body.appendChild(link);
      link.click();
      document.body.removeChild(link);
      window.URL.revokeObjectURL(url);
      ElMessage.success('导出成功');
    } else {
      ElMessage.error('导出失败');
    }
  } catch (error) {
    console.error('导出错误:', error);
    ElMessage.error('导出失败');
  } finally {
    loading.value = false;
  }
};
const getJobList = () => {
  console.log('formInline', formInline);

  pageListTamplate(formInline).then((res) => {
    if (res.data.records && res.data.records.length > 0) {
      tableData.value = res.data.records;

      pagination.total = res.data.total;
    } else {
      tableData.value = [];
    }
  });
};
const handleQuery = () => {
  getJobList();
};
const sizeChange = (size) => {
  console.log('size', size);
  pagination.limit = size.limit;
  formInline.pageNum = 1;
  formInline.pageSize = size.limit;
  pagination.page = 1;
  getJobList();
};
const currentChange = (page) => {
  formInline.pageNum = page.page;
  formInline.pageSize = pagination.limit;
  pagination.page = page.page;
  getJobList();
};
// 查看
const handleInfo = (row) => {
  console.log('row', row);

  openType.value = 'info';
  dialogVisible.value = true;
  formData.name = row.name;
  formData.createName = row.createName;
  formData.createTime = row.createTime;
  formData.version = row.version;
  formData.affiliatedModule = row.affiliatedModule;
  formData.industry = row.industry;
  formData.file = row.file;
  formData.remarks = row.remarks;
};
// 处理预览事件
const handleGetApplication = (row) => {
  // row.file 是后端返回的文件路径
  previewDocxRef.value.open(row.file);
};
const handlePreviewFile = () => {
  if (formData.file) {
    previewDocxRef.value.open(formData.file);
  } else {
    ElMessage.warning('暂无可预览的文件');
  }
};
</script>
<style lang="scss" scoped>
.search {
  display: flex;
  justify-content: space-between;

  // align-items: center;
  .button {
    margin-top: 10px;
    display: flex;
    justify-content: flex-end;
  }

}

.dialog-title {
  display: flex;
  align-items: center;
}

.dialog-title-bar {
  width: 4px;
  height: 22px;
  background: #409EFF;
  border-radius: 2px;
  margin-right: 10px;
  display: inline-block;
}

.dialog-title-text {
  font-size: 18px;
  font-weight: bold;
  color: #333;
}
</style>